using System;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using static QntPlatform.Strategy.TvCmdHandler;
using System.Collections.Specialized;

namespace QntPlatform.Strategy.CmdCtrl
{
    /// <summary>
    /// 固定止损
    /// </summary>
    public class StopLoss : CmdHandlePart
    {
        private readonly AutoSellOrder autoSellOrder;

        //止损数据，执行方法

        public StopLoss(AutoSellOrder autoSellOrder, IStrategy parent) : base(parent)
        {
            this.autoSellOrder = autoSellOrder;
            Data=new StopLossInfo(){StopLossPrice=autoSellOrder.StopLossPrice, IsCloseBuy=autoSellOrder.Direction == SideDirection.CloseBuy,Amount=autoSellOrder.Amount};
            Data.Info=autoSellOrder;
            //new  MiddleGuoup<CmdContext>().AddUse(new TrailingGroup3(null).Execute).Bulid().Invoke(null)
        }
        public class StopLossInfo
        {
            public decimal StopLossPrice{get;set;}
            public bool IsCloseBuy{get;set;}
            public decimal Amount{get;set;}
            public Object Info{get;set;}
            public string Sid { get; set; }
            public string SourceOrderId { get; set; }

            public string CreateSid(object baseId) {
                if (baseId is IConvertible)
                {
                    return baseId + "-" + this.GetHashCode();
                }
                return baseId.GetHashCode() + "-" + this.GetHashCode();
            }
        }
         public StopLossInfo Data{get;internal set;}
        public StopLoss(IStrategy parent,StopLossInfo info) : base(parent){
       
               Data=info;
            
        }
        public bool Execute(Ticker tck)
        {
            
            //检查止损
            if (ISysFun.calcUnitProfit(tck.Buy, Data.StopLossPrice, Data.IsCloseBuy) <= 0)
            {
                //NameValueCollection name1;
                log.Debug("止损交易", new { tck, Data });
               //var id= execTrade(DirectionTo.CloseFor(Data.IsCloseBuy), Data.Amount,Data);
              var id=  Exchange.CreateOrder(Data.Amount, DirectionTo.CloseFor(Data.IsCloseBuy), info: new Db.LogInfo() {  ParentActId= Data.SourceOrderId +"",Info2="止损,市价:"+tck.Buy}).Result;
                if (id != null)
                {
                    // todo  退出方案需完善
                   // Parent.OnExit();
                    return true;
                }
                return true;
            }
            return false;
        }
    }
}
